<template>
  <div style="background-color: var(--el-bg-color);border-radius: 12px;">
    <h4 v-if="title">{{ title }}</h4>
    <div class="tableupside edit" :style="$slots.edit || instance.editButton ? 'padding:10px 20px' : ''">
      <slot name="edit"></slot>
      <template v-if="instance.editButton" v-for="item in instance.editButton(false)">
        <component :is="item"></component>
      </template>
    </div>
    <el-table :data="list" style="width: 100%" :border="instance.border" :row-key="instance.rowkey"
      ref="multipleTableRef" header-row-class-name="tableheader" :tree-props="{ children: instance.children }"
      :header-cell-style="{ textAlign: instance.headerAlign }" :cell-style="{ padding: `${instance.spance}px 0` }"
      tooltip-effect="light" @selection-change="handleSelectionChange"
      @cell-mouse-enter="(e: any) => emit('cell-mouse-enter', e)"
      @cell-mouse-leave="(e: any) => emit('cell-mouse-leave', e)">
      <slot name="after"></slot>
      <el-table-column type="selection" width="55" align="center" v-if="instance.select" />
      <template v-for="item, index in labels">
        <template v-if="item">
          <el-table-column :key="index"
            v-if="!item.show || item.show({ type: 'list', data: undefined, isPhone: false })"
            :show-overflow-tooltip="item.overflow" :label="item.label" :width="item.width" :sortable="item.sortable">
            <template #default="{ row, $index }">
              <component :is="tableRender.render(row, item, $index)"></component>
            </template>
          </el-table-column>
        </template>
      </template>
      <slot></slot>
      <el-table-column v-if="instance.actions" label="操作">
        <template #default="{ row, $index }">
          <component :is="renderButton(row, $index)"></component>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination style="padding: 0 10px 10px" v-model:current-page="current" layout="prev, pager, next, jumper"
      :total="Number(instance.total)" :page-size="instance.limit" hide-on-single-page>
    </el-pagination>
    <!-- 分页消失时补位 -->
    <div v-if="instance.total <= instance.limit" style="height: 36px"></div>
    <div class="clearboth"></div>
  </div>
</template>

<script lang="ts" setup generic="T extends Record<string,any>">
import { onMounted, ref, useTemplateRef, watch, computed, h, type VNode } from "vue";
import { ElTable, ElTableColumn, ElPagination, ElButton, type TableRefs } from "element-plus";
import bDelete from "../widget/b_delete.vue";
import { List } from "@b/model/base/list";
import { TableRender } from "./render_item"
import type { listButton } from "@b/model/base/type";

interface prop {
  instance: List<T>;
  title?: string;
}
const { instance } = defineProps<prop>();
const list = computed(() => instance.list)
const labels = computed(() => Object.values(instance.labels).sort((a, b) => (a.sortBy || Infinity) - (b.sortBy || Infinity)))
const tableRender = new TableRender<T, keyof T & string>();

const emit = defineEmits([
  "cell-mouse-enter",
  "cell-mouse-leave",
]);
const multipleTableRef = useTemplateRef<TableRefs>("multipleTableRef");
const current = ref(1);

instance.select?.forEach((item: T) => {
  multipleTableRef.value?.toggleRowSelection(item);
});
watch(current, (value: number) => {
  instance.refresh(value);
});

const handleSelectionChange = (val: T[]) => {
  instance.setSelectList(val);
};
const renderButton = (data: T, index: number) => {
  const actions = instance.actions ? instance.actions({ isPhone: false, data, index }) : []
  const buttons: VNode[] = []
  const button = (action: listButton<T>) => {
    if (!action) return
    const btn = h(ElButton, {
      class: action.className || '',
      type: action.type || 'default',
      disabled: action.disabled,
    }, {
      default: () => action.text
    })
    if (action.hasConfirm) {
      return h(bDelete, {
        text: action.confirmText || '确认操作',
        disabled: action.disabled,
        onConfirm: () => action.onClick(data, index)
      }, {
        default: () => btn
      })
    } else {
      return h('span', {
        onClick: () => action.onClick(data, index)
      }, btn)
    }
  }
  actions.forEach(item => {
    const but = button(item)
    but && buttons.push(but)
  })
  return h('div', { class: 'button-group' }, buttons)
}
onMounted(() => {
  if (instance.immediateCheck) {
    if (instance.hasPages)
      instance.getPage();
    else
      instance.getList();
  }
});
</script>
<style scoped>
h4 {
  padding-bottom: 8px;
}

.el-table :deep(.el-table__cell) {
  z-index: auto;
}

.tableupside {
  display: flex;
  width: 100%;
  padding: 0 20px;
  font-size: 0.9em;
}

.clearboth {
  clear: both;
}
</style>